package com.cnguifang.feigewallet.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMConversation.EMConversationType;
import com.cnguifang.feigewallet.Constant;
import com.cnguifang.feigewallet.R;
import com.cnguifang.feigewallet.db.InviteMessgeDao;
import com.hyphenate.easeui.model.EaseAtMessageHelper;
import com.hyphenate.easeui.model.EaseDingMessageHelper;
import com.hyphenate.easeui.ui.EaseConversationListFragment;
import com.hyphenate.util.NetUtils;

import java.util.Locale;

import static android.content.ContentValues.TAG;

public class ConversationListFragment extends EaseConversationListFragment{

    private TextView errorText;
    protected RelativeLayout rightLayout;
    protected ImageView right_image;

    private int language_id=0;

    @Override
    protected void initView() {
        super.initView();
        View errorView = (LinearLayout) View.inflate(getActivity(),R.layout.em_chat_neterror_item, null);
        errorItemContainer.addView(errorView);
        errorText = (TextView) errorView.findViewById(R.id.tv_connect_errormsg);
        right_image= (ImageView) getView().findViewById(com.hyphenate.easeui.R.id.right_image);
    }
    
    @Override
    protected void setUpView() {
        super.setUpView();
        // register context menu
        registerForContextMenu(conversationListView);
        conversationListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                EMConversation conversation = conversationListView.getItem(position);
                String username = conversation.conversationId();
                if (username.equals(EMClient.getInstance().getCurrentUser()))
                    Toast.makeText(getActivity(), R.string.Cant_chat_with_yourself, Toast.LENGTH_SHORT).show();
                else {
                    // start chat acitivity
                    Intent intent = new Intent(getActivity(), ChatActivity.class);
                    if(conversation.isGroup()){
                        if(conversation.getType() == EMConversationType.ChatRoom){
                            // it's group chat
                            intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_CHATROOM);
                        }else{
                            intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_GROUP);
                        }
                        
                    }
                    // it's single chat
                    intent.putExtra(Constant.EXTRA_USER_ID, username);
                    startActivity(intent);
                }
            }
        });
        right_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String[] language = getActivity().getResources().getStringArray(R.array
                        .language_choice);
                final SharedPreferences sharedPreferences = getActivity().getSharedPreferences
                        ("language_choice", getActivity().MODE_PRIVATE);
                final int id = sharedPreferences.getInt("language_id", 0);


                final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("语言设置");
                builder.setSingleChoiceItems(language, id, new DialogInterface
                        .OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                // default
                                language_id = 0;
                                break;
                            case 1:
                                language_id = 1;
                                // english
                                break;
                            default:
                                //default
                                language_id = 0;
                                break;
                        }
                        sharedPreferences.edit().putInt("language_id", language_id).commit();
                    }
                });
                builder.setPositiveButton("确认", new DialogInterface
                        .OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent=new Intent();
                        intent.setClass(getActivity(),SplashActivity.class);
                        getActivity().startActivity(intent);
                        getActivity().finish();
                        setLanguage();// 必须加上，否者不会更新语言
                    } });

                builder.show();
            }
        });
        super.setUpView();
    }

    private void setLanguage() {
        Resources resources=getResources();
        final SharedPreferences sharedPreferences=getActivity().getSharedPreferences("language_choice", getActivity()
                .MODE_PRIVATE);
        language_id = sharedPreferences.getInt("language_id", 0);
        Log.e(TAG,"language_id=="+language_id);
        // 获取应用内语言
        final Configuration configuration=resources.getConfiguration();
//        Locale locale=configuration.locale;
        DisplayMetrics displayMetrics=resources.getDisplayMetrics();
        switch (language_id){
            case 0:
                configuration.locale= Locale.getDefault();
                break;
            case 1:
                configuration.locale=Locale.SIMPLIFIED_CHINESE;
                break;
            default:
                configuration.locale=Locale.getDefault();
                break;
        }
        Log.e(TAG,"configuration=="+configuration.locale);
        getResources().updateConfiguration(configuration,displayMetrics);
    }

    @Override
    protected void onConnectionDisconnected() {
        super.onConnectionDisconnected();
        if (NetUtils.hasNetwork(getActivity())){
         errorText.setText(R.string.can_not_connect_chat_server_connection);
        } else {
          errorText.setText(R.string.the_current_network);
        }
    }
    
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        getActivity().getMenuInflater().inflate(R.menu.em_delete_message, menu); 
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        boolean deleteMessage = false;
        if (item.getItemId() == R.id.delete_message) {
            deleteMessage = true;
        } else if (item.getItemId() == R.id.delete_conversation) {
            deleteMessage = false;
        }
    	EMConversation tobeDeleteCons = conversationListView.getItem(((AdapterContextMenuInfo) item.getMenuInfo()).position);
    	if (tobeDeleteCons == null) {
    	    return true;
    	}
        if(tobeDeleteCons.getType() == EMConversationType.GroupChat){
            EaseAtMessageHelper.get().removeAtMeGroup(tobeDeleteCons.conversationId());
        }
        try {
            // delete conversation
            EMClient.getInstance().chatManager().deleteConversation(tobeDeleteCons.conversationId(), deleteMessage);
            InviteMessgeDao inviteMessgeDao = new InviteMessgeDao(getActivity());
            inviteMessgeDao.deleteMessage(tobeDeleteCons.conversationId());
            // To delete the native stored adked users in this conversation.
            if (deleteMessage) {
                EaseDingMessageHelper.get().delete(tobeDeleteCons);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        refresh();

        // update unread count
        ((MainActivity) getActivity()).updateUnreadLabel();
        return true;
    }

}
